<?php

namespace app\index\controller;

use app\admin\model\echartsapp\AreaMap;
use app\common\controller\Frontend;
use think\Db;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        return $this->view->fetch();
    }

    public function news()
    {
        $newslist = [];
        return jsonp(['newslist' => $newslist, 'new' => count($newslist), 'url' => 'https://www.fastadmin.net?ref=news']);
    }

    public function importJson (AreaMap $areaMapModel){
      $pid = 0;
      $areas = ['100000'=>['name'=>'中国','adcode'=>'100000', 'lng'=>0.000000,'lat'=>0.000000]];

//      $this->readJson($areas);
      $this->insertJson($areas, $areas['100000'], $pid);

      return json_encode( $areas,JSON_UNESCAPED_UNICODE);
    }

  private function insertJson(&$areas, $area, $pid = 0){
      if (!isset( $area['adcode'])) return;

      $area['pid'] = $pid;
    $file = ROOT_PATH.'/public/assets/china-map/'.$area['adcode'].'.json';

    if (!is_file( $file)) {
      return DB::name( 'echartsapp_area_map')->insertGetId( $area);
    }

    $content = file_get_contents( $file);
    $contentJson = json_decode( $content, true);

    $area['map'] = $content;
    $pid = DB::name( 'echartsapp_area_map')->insertGetId( $area);

    foreach ($contentJson['features'] as $item) {
      $properties = $item['properties'];

      $canRead = true;
      $name =$properties['name'];
      $adcode =$properties['adcode'];
      $lng =$properties['center'][0] ?? ($properties['center']['lng'] ?? 0.000000);
      $lat =$properties['center'][1] ?? ($properties['center']['lat'] ?? 0.000000);

      if (empty( $name) || array_key_exists( $adcode, $areas)) $canRead = false;

      if ($canRead){
        $areas[$adcode]=compact( 'name','adcode','lng','lat');
        $this->insertJson($areas, $areas[$adcode], $pid);
      }
    }
  }

  private function readJson(&$areas, $adcode = '100000'){
    $file = ROOT_PATH.'/public/assets/china-map/'.$adcode.'.json';

    if (!is_file( $file)) return;

    $content = file_get_contents( $file);
    $contentJson = json_decode( $content, true);

    foreach ($contentJson['features'] as $k => $item) {
      $properties = $item['properties'];

      $canRead = true;
      $name =$properties['name'];
      $adcode =$properties['adcode'];
      $lng =$properties['center'][0] ?? ($properties['center']['lng'] ?? 0.000000);
      $lat =$properties['center'][1] ?? ($properties['center']['lat'] ?? 0.000000);

      if (empty( $name)) continue;

      if (array_key_exists( $adcode, $areas)) $canRead = false;

      if ($canRead){
        $areas[$adcode]=compact( 'name','adcode','lng','lat');
        $this->readJson($areas, $adcode);
      }
    }
  }

}
